package dfbz.线程锁2;
/*
 * 解决线程安全问题：
 *   1、同步方法
 *       1.1 非静态同步方法  锁对象是this
 *       权限修饰符 synchronized 返回值类型 方法名(){}
 *       1.2 静态同步方法  锁对象是当前类的class属性  (反射技术)  类名.class
 *       权限修饰符 static synchronized 返回值类型 方法名(){}

 * */
public class RunnableImpl implements Runnable {
    //票的总数
    private static Integer ticket=100;
    //定义锁对象
    private static Object obj=new Object();

    @Override
    public void run() {
        while (true){
            method04();
        }
    }

    public static void method04(){
        synchronized (RunnableImpl.class){
            //买票
            if (ticket>0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //打印当前卖出的票
                System.out.println(Thread.currentThread().getName() + "正在卖第: " + ticket + "张票");
                //票数减1
                ticket--;
            }
        }
    }

    public static synchronized void method03(){
        //买票
        if (ticket>0){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //打印当前卖出的票
            System.out.println(Thread.currentThread().getName() + "正在卖第: " + ticket + "张票");
            //票数减1
            ticket--;
        }
    }

    public void method02(){
        synchronized (this){
            //买票
            if (ticket>0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //打印当前卖出的票
                System.out.println(Thread.currentThread().getName() + "正在卖第: " + ticket + "张票");
                //票数减1
                ticket--;
            }
        }
    }

    public synchronized void method01(){
        //买票
        if (ticket>0){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //打印当前卖出的票
            System.out.println(Thread.currentThread().getName() + "正在卖第: " + ticket + "张票");
            //票数减1
            ticket--;
        }
    }
}
